package com.huadragon.marathoncore.util;



import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class StatusUtil {
	private static StatusUtil instance;
	private final Map<String, String> messageDictionary;
	
	protected StatusUtil() throws DocumentException{	
		messageDictionary=new HashMap<String, String>();
		
//		try {
			Document doc=parse("/status.xml");
			
			Element root = doc.getRootElement();

			  Iterator it = root.elementIterator();
			  while (it.hasNext()) {
			   Element element = (Element) it.next();

			   //未知属性名称情况下
			   /*Iterator attrIt = element.attributeIterator();
			   while (attrIt.hasNext()) {
			    Attribute a  = (Attribute) attrIt.next();
			    System.out.println(a.getValue());
			   }*/

			   //已知属性名称情况下
			   //System.out.println("id: " + element.attributeValue("id"));
			   
			   messageDictionary.put(element.attributeValue("code"), element.attributeValue("message"));
			  }
//		} catch (Exception e) {
//			// TODO: handle exception
//            e.printStackTrace();
//		}
	}
	
	public static StatusUtil GetInstance() throws DocumentException
    {
		if(instance==null)
           instance=new StatusUtil();
		return instance;
    }
	
	public String GetMessage(String statusCode)
    {
		//return messageDictionary.getOrDefault(statusCode, "");
		return messageDictionary.get(statusCode);
    }
	
	private Document parse(String fileName) throws DocumentException {
		ClassLoader classLoader = getClass().getClassLoader();  
	    File file = new File(classLoader.getResource(fileName).getFile());
	    
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
        return document;
    }
}
